package controllers

import (
	"fmt"
	"myapp/dal/model"
	"myapp/dal/query"
	"myapp/middleware"
	"myapp/pkg"
	"myapp/validates"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"gorm.io/gorm"
)

func PostHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id := 0
		if len(c.Query("id")) > 0 {
			id, _ = strconv.Atoi(c.Query("id"))
		}

		var dto validates.Need
		if err := c.ShouldBindJSON(&dto); err != nil {
			errs, ok := err.(validator.ValidationErrors)
			if !ok {
				// 非validator.ValidationErrors类型错误直接返回
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  err.Error(),
				})
				return
			}
			// validator.ValidationErrors类型错误则进行翻译
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  middleware.GetFirstErrorMessage(errs),
			})
			return
		}

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {
			user, _ := query.User.Where(query.User.ID.Eq(int32(v))).Take()
			if len(user.Company) < 1 {
				c.JSON(http.StatusOK, gin.H{
					"code": 110,
					"msg":  "对不起，请将个人资料补充完整再提交",
				})
				return
			}

			now := time.Now()
			twentyFourHoursAgo := now.Add(-24 * time.Hour)

			count, _ := query.Need.Where(query.Need.UserID.Eq(int32(v)), query.Need.Status.Eq(0), query.Need.CreatedAt.Gte(twentyFourHoursAgo)).Count()
			if count >= 10 && id == 0 {
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  "对不起，您有信息还在审核中，请不要重复提交",
				})
				return
			}

			images := strings.Join(dto.Images, ",")
			nd := model.Need{
				Title:       dto.Title,
				Type:        int32(dto.Type),
				Content:     dto.Content,
				Company:     dto.Company,
				Images:      images,
				CategoryIds: dto.CategoryIds,
			}

			isWhite, _ := query.Whitelist.Where(query.Whitelist.Phone.Eq(user.Username)).Count()
			if isWhite > 0 {
				nd.IsWhite = 1
			}

			queryStr := dto.Title + "\n" + dto.Company

			// 执行翻译
			result, err := pkg.Translate(queryStr)
			if err != nil {
				fmt.Println("Error:", err)
				return
			}

			// 打印翻译结果
			fmt.Println("翻译结果:", result)

			for k, v := range result.TransResult {
				fmt.Println(k, v.Src, v.Dst)

				if v.Src == dto.Title {
					nd.TitleEn = v.Dst
				}

				if v.Src == dto.Company {
					nd.CompanyEn = v.Dst
				}
			}

			//内容太多，单独翻译
			result, err = pkg.Translate(dto.Content)
			if err != nil {
				fmt.Println("Error:", err)
				return
			}

			for k, v := range result.TransResult {
				fmt.Println(k, v.Src, v.Dst)
				nd.ContentEn = v.Dst
			}

			nd.UserID = int32(v)

			if id != 0 {
				query.Need.Where(query.Need.ID.Eq(int32(id)), query.Need.UserID.Eq(int32(v))).Updates(nd)
			} else {
				query.Need.Create(&nd)
			}

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": nd.ID})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})
	}
}

func JoinHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		var dto validates.Join
		if err := c.ShouldBindJSON(&dto); err != nil {
			errs, ok := err.(validator.ValidationErrors)
			if !ok {
				// 非validator.ValidationErrors类型错误直接返回
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  err.Error(),
				})
				return
			}
			// validator.ValidationErrors类型错误则进行翻译
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  middleware.GetFirstErrorMessage(errs),
			})
			return
		}

		need, _ := query.Need.Where(query.Need.ID.Eq(int32(dto.NeedId))).Take()
		if need.Status != 1 {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "对不起，该信息不存在或未上架",
			})
			return
		}

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {
			user, _ := query.User.Where(query.User.ID.Eq(int32(v))).Take()
			if len(user.Company) < 1 {
				c.JSON(http.StatusOK, gin.H{
					"code": 110,
					"msg":  "对不起，请将个人资料补充完整再提交",
				})
				return
			}

			count, _ := query.Join.Where(query.Join.NeedID.Eq(int32(dto.NeedId)), query.Join.Type.Eq(int32(dto.Type)), query.Join.UserID.Eq(int32(v))).Count()
			if count > 0 {
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  "对不起，您已经对该信息感兴趣过了",
				})
				return
			}

			nd := model.Join{
				NeedID:   int32(dto.NeedId),
				Name:     dto.Name,
				Company:  dto.Company,
				Position: dto.Position,
				Phone:    dto.Contact,
				Message:  dto.Message,
				UserID:   int32(v),
				Type:     int32(dto.Type),
			}

			query.Join.Create(&nd)

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": nd.ID})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})
	}
}

func JoinUnionHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		var dto validates.JoinUnion
		if err := c.ShouldBindJSON(&dto); err != nil {
			errs, ok := err.(validator.ValidationErrors)
			if !ok {
				// 非validator.ValidationErrors类型错误直接返回
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  err.Error(),
				})
				return
			}
			// validator.ValidationErrors类型错误则进行翻译
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  middleware.GetFirstErrorMessage(errs),
			})
			return
		}

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {
			nd := model.JoinUnion{
				Name:     dto.Name,
				Company:  dto.Company,
				Position: dto.Position,
				Phone:    dto.Contact,
				UserID:   int32(v),
			}

			query.JoinUnion.Create(&nd)

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": nd.ID})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})
	}
}

func InterestHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		locale, _ := c.GetQuery("locale")
		category_id, _ := c.GetQuery("category_id")
		keyword, _ := c.GetQuery("keyword")
		typestr, _ := c.GetQuery("type")
		typestr1, _ := strconv.Atoi(typestr)

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		userId, _ := c.Get("userID")
		var uid uint
		if v, ok := userId.(uint); ok {
			uid = v
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "程序异常",
			})
		}

		if typestr1 == 1 {
			querys := query.Member.Join(query.Join, query.Join.NeedID.EqCol(query.Member.ID)).Where(query.Join.UserID.Eq(int32(uid)))
			if len(category_id) > 0 {
				querys = querys.Where(query.Member.MemberCategoryIds.FindInSetWith(category_id))
			}

			if len(keyword) > 0 {
				if locale == "en_US" {
					querys = querys.Where(query.Member.NameEn.Like("%" + keyword + "%"))
				} else {
					querys = querys.Where(query.Member.Name.Like("%" + keyword + "%"))
				}
			}

			if len(typestr) > 0 {
				querys = querys.Where(query.Join.Type.Eq(int32(typestr1)))
			}

			offset := (page1 - 1) * 10
			needs, _, _ := querys.Order(query.Join.ID.Desc()).FindByPage(offset, 10)

			// 将查询结果转换为自定义结构体
			var customNeeds []validates.Member
			for _, need := range needs {
				customNeeds = append(customNeeds, validates.ProcessMember(need))
			}

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
				"needs": customNeeds,
			}})
		} else {
			querys := query.Need.Join(query.Join, query.Join.NeedID.EqCol(query.Need.ID)).Where(query.Join.UserID.Eq(int32(uid)))
			if len(category_id) > 0 {
				querys = querys.Where(query.Need.CategoryIds.FindInSetWith(category_id))
			}

			if len(keyword) > 0 {
				if locale == "en_US" {
					querys = querys.Where(query.Need.TitleEn.Like("%" + keyword + "%"))
				} else {
					querys = querys.Where(query.Need.Title.Like("%" + keyword + "%"))
				}
			}

			if len(typestr) > 0 {
				querys = querys.Where(query.Join.Type.Eq(int32(typestr1)))
			}

			offset := (page1 - 1) * 10
			needs, _, _ := querys.Order(query.Join.ID.Desc()).FindByPage(offset, 10)

			// 将查询结果转换为自定义结构体
			var customNeeds []validates.Need
			for _, need := range needs {
				customNeeds = append(customNeeds, validates.ProcessNeed(need))
			}

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
				"needs": customNeeds,
			}})
		}
	}
}

func MyNeedsHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		locale, _ := c.GetQuery("locale")
		category_id, _ := c.GetQuery("category_id")
		keyword, _ := c.GetQuery("keyword")
		typestr, _ := c.GetQuery("type")
		typestr1, _ := strconv.Atoi(typestr)

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		userId, _ := c.Get("userID")
		var uid uint
		if v, ok := userId.(uint); ok {
			uid = v
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "程序异常",
			})
		}
		query.Need.CreatedAt.DateFormat("%W %M %Y")

		querys := query.Need.Where(query.Need.UserID.Eq(int32(uid)))
		if len(category_id) > 0 {
			querys = querys.Where(query.Need.CategoryIds.FindInSetWith(category_id))
		}

		if len(keyword) > 0 {
			if locale == "en_US" {
				querys = querys.Where(query.Need.TitleEn.Like("%" + keyword + "%"))
			} else {
				querys = querys.Where(query.Need.Title.Like("%" + keyword + "%"))
			}
		}

		if len(typestr) > 0 {
			querys = querys.Where(query.Need.Type.Eq(int32(typestr1)))
		}

		offset := (page1 - 1) * 10
		needs, _, _ := querys.Order(query.Need.ID.Desc()).FindByPage(offset, 10)

		// 将查询结果转换为自定义结构体
		var customNeeds []validates.Need
		for _, need := range needs {
			customNeeds = append(customNeeds, validates.ProcessNeed(need))
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs": customNeeds,
		}})
	}
}

func MyNeedDelHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id, _ := strconv.Atoi(c.Param("id"))

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {

			query.Need.Where(query.Need.ID.Eq(int32(id)), query.Need.UserID.Eq(int32(v))).Delete()
			c.JSON(http.StatusOK, gin.H{"code": 0})
			return

		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})
	}
}
